﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using FastReport;
using Center.core;
using Center.lib.utils.json;
using Center.lib.utils.http;
using Center.lib.utils.log;
using System.IO;
using PrinterApplication.frmbase;
using PrinterApplication.control;
using System.Threading;
using PrinterApplication.report;
using Center.lib.utils.common;
using ahdelivery.util;
using PrinterApplication.util;
using Sunny.UI;

namespace PrinterApplication
{
    public partial class CenterFrm : BaseFrm
    {
        private Thread myth;
        private Boolean hasBatcode = false;
        private string localFilePath = "", fileNameExt = "", newFileName = "", FilePath = "";
        private String strOrderBy;
        private DataTable dt { get; set; }
        private OrderSearchDTO search;
        private RestModel<List<CommodityOrderDTO>> orderDatas;
        private ListResult<String> provinces;
        private List<String> deliverTypeNames;
        private delegate void _addPrivince(string p);
        private delegate void _addPrivinceComBox();
        private delegate void _addProductComBox();
        private delegate void _showPanel();
        private delegate void _hidePanel();
        private delegate void _setData();
        private delegate void _labelset();
        private delegate void _totalPage();
        private delegate void _setData2(DataTable dt);
        private delegate void _setCount(Int64 count);
        private delegate void _cleanData();
        private void addPrivinceDataTable()
        {
            if (this.comboBoxExProvince.InvokeRequired)
            {
                _addPrivinceComBox call = delegate ()
                {
                    this.comboBoxExProvince.DataBind();
                };
                this.comboBoxExProvince.Invoke(call);
            }
            else
            {
                this.comboBoxExProvince.DataBind();
            }
        }
        private void addProductDataTable()
        {
            if (this.comboBoxExProduct.InvokeRequired)
            {
                _addProductComBox call = delegate ()
                {
                    this.comboBoxExProduct.DataBind();
                };
                this.comboBoxExProduct.Invoke(call);
            }
            else
            {
                this.comboBoxExProduct.DataBind();
            }
        }
        private void showPanel()
        {
            if (this.exPannel1.InvokeRequired)
            {
                _showPanel call = delegate ()
                {
                    this.exPannel1.Dock = DockStyle.Fill;
                    this.exPannel1.BringToFront();
                };
                this.exPannel1.Invoke(call);
            }
            else
            {
                this.exPannel1.Dock = DockStyle.Fill;
                this.exPannel1.BringToFront();
            }
        }
        private void hidePanel()
        {
            if (this.exPannel1.InvokeRequired)
            {
                _hidePanel call = delegate ()
                {
                    this.exPannel1.SendToBack();
                };
                this.exPannel1.Invoke(call);
            }
            else
            {
                this.exPannel1.SendToBack();
            }
        }

        private void setData(DataTable dt)
        {
            this.setData2(dt);
        }

        private void setCount(Int64 count)
        {
            if (this.skinLabelCount.InvokeRequired)
            {
                _setCount call = delegate (Int64 t)
                {
                    this.skinLabelCount.Text = String.Format("数量：{0}个", count.ToString()); ;
                };
                this.skinLabelCount.Invoke(call, count);
            }
            else
            {
                this.skinLabelCount.Text = String.Format("数量：{0}个", count.ToString());
            }

        }

        private void setData2(DataTable dt)
        {
            if (this.skinDataGridView1.InvokeRequired)
            {
                _setData2 call = delegate (DataTable dataTable)
                {
                    this.setDatagrid2(dataTable);
                };
                this.skinDataGridView1.Invoke(call, dt);
            }
            else
            {
                this.setDatagrid2(dt);
            }

        }
        private void cleanData()
        {
            if (this.skinDataGridView1.InvokeRequired)
            {
                _cleanData call = delegate ()
                {
                    this.cleanDatagrid2();
                };
                this.skinDataGridView1.Invoke(call);
            }
            else
            {
                this.cleanDatagrid2();
            }

        }

        private void cleanDatagrid2()
        {
            if (this.skinDataGridView1.DataSource != null)
            {
                this.skinDataGridView1.DataSource = null;
            }
        }

        private void setDatagrid2(DataTable dt)
        {
            this.skinDataGridView1.DataSource = dt;
            this.skinDataGridView1.Update();
            this.skinDataGridView1.Refresh();
        }

        public CenterFrm()
            : base()
        {
            Console.WriteLine(JsonHelper.ToJson(search));
            InitializeComponent();
            this.init();
            this.hidePanel();
            //this.MinimizeBox = false;
        }
        private void init()
        {
            this.search = new OrderSearchDTO();
            this.search.warehouseId = util.Config.g_user.warehouseId;
            this.search.commodityCodes = ListUtils.copyString(util.Config.g_user.commodityCodes);
            this.skinDataGridView1.ReadOnly = true;
            this.skinDataGridView1.AllowUserToAddRows = false;
            this.deliverTypeNames = new List<string>();
            this.deliverTypeNames.Add("申通");
            this.deliverTypeNames.Add("邮政");
            this.deliverTypeNames.Add("韵达");
            this.deliverTypeNames.Add("中通");
            this.deliverTypeNames.Add("圆通");
            dt = new DataTable();
            dt.Columns.Add("批次号", typeof(string));
            dt.Columns.Add("序号", typeof(string));
            dt.Columns.Add("平台类型", typeof(string));
            dt.Columns.Add("订单编号", typeof(string));
            dt.Columns.Add("收货人姓名", typeof(string));
            dt.Columns.Add("收货人电话", typeof(string));
            dt.Columns.Add("省", typeof(string));
            dt.Columns.Add("市", typeof(string));
            dt.Columns.Add("区", typeof(string));
            dt.Columns.Add("详细地址", typeof(string));
            dt.Columns.Add("快递单号", typeof(string));
            dt.Columns.Add("快递", typeof(string));
            dt.Columns.Add("商品编码", typeof(string));
            dt.Columns.Add("商品名", typeof(string));
            dt.Columns.Add("状态", typeof(string));
            dt.Columns.Add("订单时间", typeof(string));
            dt.Columns.Add("一段码", typeof(string));
            dt.Columns.Add("二三段码", typeof(string));
        }

        private void CenterFrm_Load(object sender, EventArgs e)
        {
            ControllerBuffer.DoubleBuffered(this.skinDataGridView1, true);
            //ControllerBuffer.DoubleBuffered(this.exPannel1, true);
            this.skinComboBox2.Items.Add("未打印");
            this.skinComboBox2.Items.Add("已打印");
            this.skinComboBox2.SelectedIndex = 0;
            this.skinComboBoxType.Items.Add("请选择");
            this.skinComboBoxType.Items.Add("淘宝");
            this.skinComboBoxType.Items.Add("拼多多");
            this.skinComboBoxType.SelectedIndex = 0;
            this.hidePanel();
            this.getProduct();
            new Task(() =>
            {
                this.getData();
            }).Start();
            new Task(() =>
            {
                this.getProvince();
            }).Start();
            this.txtStartTime.Text = DateTime.Now.AddMinutes(-20).ToString("yyyy-MM-dd HH:mm:00");
            this.txtEndTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:00");
            this.search.startTime = this.txtStartTime.Text;
            this.search.endTime = this.txtEndTime.Text;
            this.txtDeliveryCode.KeyPress += anyTextBox_KeyPress;
            this.txtOrderCode.KeyPress += anyTextBox_KeyPress;
        }

        private void anyTextBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == '\x1')
            {
                ((TextBox)sender).SelectAll();
                e.Handled = true;
            }
        }

        private async void getData()
        {
            if (this.search.commodityCodes.Count == 0)
            {
                this.search.commodityCodes = ListUtils.copyString(util.Config.g_user.commodityCodes);
            }
            this.showPanel();
            this.SearchData();
            this.hidePanel();

        }

        private async void SearchData()
        {
            try
            {
                this.showPanel();
                DataTable t = dt.Clone();
                t.Clear();

                Dictionary<String, String> headers = new Dictionary<string, string>();
                headers.Add("token", util.Config.g_user.token);
                headers.Add("appId", util.Config.g_user.appId);
                
                String result = await HttpUtils.PostData( util.Config.URI_FETCH_COMMODITYS, search, headers);
                LogHelper.WriteLog(JsonHelper.ToJson(search));
                this.orderDatas = JsonHelper.FromJson<RestModel<List<CommodityOrderDTO>>>(result);
                orderDatas.data.ForEach((p) =>
                {
                    var dr = t.NewRow();
                    if (string.IsNullOrEmpty(p.expressPrintBatchNo))
                    {
                        hasBatcode = false;
                    }
                    else
                    {
                        hasBatcode = true;
                    }
                    dr["批次号"] = p.expressPrintBatchNo;
                    dr["序号"] = p.expressPrintSerial.ToString();
                    dr["平台类型"] = p.platformName;
                    dr["订单编号"] = p.orderNo;
                    dr["收货人姓名"] = p.consignee;
                    dr["收货人电话"] = p.receivingPhone.ToString();
                    dr["省"] = p.receivingProvince;
                    dr["市"] = p.receivingCity;
                    dr["区"] = p.receivingDistrict;
                    dr["详细地址"] = p.receivingAddress;
                    dr["快递单号"] = p.expressNo;
                    dr["快递"] = p.expressName;
                    dr["商品编码"] = p.commodityCode.ToString();
                    dr["商品名"] = p.commodityTitle.ToString();
                    if (p.expressPrint == 1)
                    {
                        dr["状态"] = "已打印";
                    }
                    else
                    {
                        dr["状态"] = "未打印";
                    }

                    dr["订单时间"] = DateUtils.GetDateTime(p.created);
                    dr["一段码"] = p.sectionCode1 == null ? "" : p.sectionCode1.ToString();
                    String lastCode = String.Format("{0}", p.sectionCode2);
                    dr["二三段码"] = lastCode;
                    t.Rows.Add(dr);
                });
                this.setData(t);
                this.setCount(t.Rows.Count);
            }
            catch (Exception e)
            {
                LogHelper.WriteLog("获取订单信息异常",e);
                UIMessageBox.ShowError("获取订单信息异常");
            }
        }

        // 更新打印状态
        private async void updatePrintStatus(DataTable dt)
        {
            List<PrintStatusDTO> pDtos = new List<PrintStatusDTO>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                PrintStatusDTO pDto = new PrintStatusDTO();
                pDto.orderNo = dt.Rows[i]["订单编号"].ToString();
                pDto.printBatchNo = dt.Rows[i]["批次号"].ToString();
                pDto.serialNo = Convert.ToInt32(dt.Rows[i]["序号"].ToString());
                pDto.printStatus =1;
                pDtos.Add(pDto);
            }

            Dictionary<String, String> headers = new Dictionary<string, string>();
            headers.Add("token", util.Config.g_user.token);
            headers.Add("appId", util.Config.g_user.appId);

            String result = await HttpUtils.PostData(util.Config.URI_UPDATE_PRINT_STATUS, pDtos, headers);
            LogHelper.WriteLog(result);
            Result ret = JsonHelper.FromJson<Result>(result);
            if (ret.code == 200)
            {
                UIMessageBox.ShowSuccess(ret.msg);
            } else
            {
                UIMessageBox.ShowError(ret.msg, true);
            }
        }
        public DataTable LinqSortDataTable(DataTable tmpDt)
        {
            DataTable dtsort = tmpDt.Clone();
            dtsort = tmpDt.Select("", this.strOrderBy).CopyToDataTable();
            return dtsort;
        }

        private void CreateReport(bool tfDesigin)
        {
            if (MessageBox.Show(@"确定打印吗？", @"提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                int index = 0;
                this.showPanel();
                string path = Application.StartupPath;
                Report report = new Report();
                string strDirectory = path + "\\ReportFiles";
                string frx = Constant.COMMON_FRX;
                // 判断是否为圆通快递
                if (Config.g_user.expressCode== "yt")
                {
                    frx = Constant.YT_FRX;
                }
                if (!Directory.Exists(strDirectory))
                {
                    Directory.CreateDirectory(strDirectory);
                }
                if (!File.Exists(strDirectory + frx))
                {
                    report.FileName = strDirectory + frx;
                }
                else
                {
                    report.Load(strDirectory + frx);
                }
                DataTable dtt = (DataTable)this.skinDataGridView1.DataSource;
                DataRow[] rows = dtt.Select("", this.strOrderBy);
                DataTable t = dtt.Clone();
                t.Clear();
                foreach (DataRow row in rows)
                {
                    t.ImportRow(row);
                }
                DataTable dt = t;
                dt.Columns.Add("总数", typeof(int));
                dt.Columns.Add("页码", typeof(int));
                dt.Columns.Add("发货人", typeof(String));
                dt.Columns.Add("发货电话", typeof(String));
                dt.Columns.Add("发货地址", typeof(String));
                dt.Columns.Add("标识", typeof(String));
                index = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    index++;
                    dr["页码"] = index;
                    dr["发货人"] = util.Config.g_user.shipper;
                    dr["发货电话"] = util.Config.g_user.shipperTel;
                    dr["发货地址"] = util.Config.g_user.province + util.Config.g_user.city+ util.Config.g_user.district + util.Config.g_user.address;
                    dr["总数"] = dt.Rows.Count;
                    if (util.Config.g_user.expressCode == "st")
                    {
                        dr["标识"] = StringUtil.cutSize(StringUtil.cutBetween(dr["二三段码"].ToString(), " "), 4);
                    }
                    else 
                    {
                        dr["标识"] = String.Empty;
                    }
                }
                dt.TableName = "ProductDetail";
                int nThreads = 200;
                int count = dt.Rows.Count % nThreads == 0 ? (dt.Rows.Count / nThreads) : (dt.Rows.Count / nThreads) + 1;
                for (int i = 0; i < count; i++)
                {
                    int start = 0;
                    int end = 0;
                    if (i == count - 1)
                    {
                        start = i * nThreads;
                        end = dt.Rows.Count;
                    }
                    else
                    {
                        start = i * nThreads;
                        end = (i + 1) * nThreads;
                    }

                    DataTable dtNew = dt.Copy();  //复制dt表数据结构
                    dtNew.Clear(); //清楚数据
                    for (int j = start; j < end; j++)
                    {
                        DataRow dr = dt.Rows[j];
                        String batchCode = String.Format("批次号{0}-{1}", dr["批次号"].ToString(), dr["序号"].ToString());
                        LogHelper.WriteLog(batchCode);
                        DataRow newDr = dtNew.NewRow();
                        newDr.ItemArray = dr.ItemArray;    //datarow为引用类型，不能直接赋值给dt，只能把行中的值一个一个复制过去
                        dtNew.Rows.Add(newDr);
                    }
                    DataSet ds = new DataSet();
                    ds.Tables.Add(dtNew);
                    report.RegisterData(ds);
                    if (tfDesigin)
                    {
                        report.Design();
                    }
                    else
                    {
                        report.PrintSettings.ShowDialog = false;
                        report.Print();
                        LogHelper.WriteLog("更新批次号");
                        new Task(() =>
                        {
                            this.updatePrintStatus(dtNew);
                        }).Start();
                    }
                }
                this.hidePanel();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            new Task(() =>
            {
                this.getData();
            }).Start();

        }


        private void button2_Click(object sender, EventArgs e)
        {
            new Task(() =>
            {
                this.CreateReport(false);
            }).Start();
        }

        private async void getProvince()
        {
            String result = await HttpUtils.PostData(util.Config.URI_FETCH_PROVINCE);
            if (!String.IsNullOrEmpty(result))
            {
                this.provinces = JsonHelper.FromJson<ListResult<String>>(result);
                List<String> list = this.provinces.list;
                list = ListUtils.listSort(list);
                DataTable dsProvince = new DataTable();
                dsProvince.Columns.Add("省份", typeof(string));
                list.ForEach(p =>
                {
                    var dr = dsProvince.NewRow();
                    dr["省份"] = p;
                    dsProvince.Rows.Add(dr);
                });
                this.comboBoxExProvince.DataSource = dsProvince;
                this.comboBoxExProvince.DisplayFiled = "省份";
                this.addPrivinceDataTable();
            }
        }
        private void getProduct()
        {
            List<String> list = ListUtils.copyString(util.Config.g_user.commodityCodes);
            DataTable dsProduct = new DataTable();
            dsProduct.Columns.Add("商品编码", typeof(string));
            list.ForEach(p =>
            {
                var dr = dsProduct.NewRow();
                dr["商品编码"] = p;
                dsProduct.Rows.Add(dr);
            });
            this.comboBoxExProduct.DataSource = dsProduct;
            this.comboBoxExProduct.DisplayFiled = "商品编码";
            this.addProductDataTable();
        }


        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            //this.setCity();
            //comboBox3.Items.Clear();
            //this.getRegion();
        }



        private void button4_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(@"确定退出？", @"提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                Application.Exit();
            }
        }

        private void skinButton2_Click(object sender, EventArgs e)
        {
            //this.CreateReport(false);
            DataTable dtt = (DataTable)this.skinDataGridView1.DataSource;
            if (String.IsNullOrEmpty(dtt.Rows[0]["批次号"].ToString()))
            {
                int index = 0;
                String batchCode = DateTime.Now.ToString("yyMMddHHmmss") + "-" + dtt.Rows.Count.ToString();
                foreach (DataRow dr in dtt.Rows)
                {
                    index++;
                    dr["序号"] = index.ToString();
                    dr["批次号"] = batchCode;
                }
                this.skinDataGridView1.Update();
            }
        }

        private void CenterFrm_FormClosing(object sender, FormClosedEventArgs e)
        {
            if (MessageBox.Show(@"确定退出？", @"提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                Application.Exit();
            }
        }

        private void label17_Click(object sender, EventArgs e)
        {

        }

        // 打印按钮操作
        private void printBtn_Click(object sender, EventArgs e)
        {
            if (!this.hasBatcode)
            {
                DataTable dtt = (DataTable)this.skinDataGridView1.DataSource;
                int index = 0;
                String batchCode = DateTime.Now.ToString("yyMMddHHmmss") + "-" + dtt.Rows.Count.ToString();
                foreach (DataRow dr in dtt.Rows)
                {
                    index++;
                    dr["序号"] = index.ToString();
                    dr["批次号"] = batchCode;
                }
                this.skinDataGridView1.Update();
            }
            LogHelper.WriteLog("开始打印");
           this.CreateReport(false);
        }

        private void searchBtn_Click(object sender, EventArgs e)
        {
            List<TreeNode> list = this.comboBoxExProvince.SelectedItems;
            this.search.provinces.Clear();
            foreach (TreeNode item in list)
            {
                this.search.provinces.Add(item.Text);
            }
            List<TreeNode> productlist = this.comboBoxExProduct.SelectedItems;
            this.search.commodityCodes.Clear();
            foreach (TreeNode item in productlist)
            {
                this.search.commodityCodes.Add(item.Text);
            }
            LogHelper.WriteLog(JsonHelper.ToJson(this.search));
            new Task(() =>
            {
                this.getData();
            }).Start();
        }

        private void skinTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void skinTextBox3_Paint(object sender, PaintEventArgs e)
        {

        }

        private void txtPhone_TextChanged(object sender, EventArgs e)
        {
            this.search.phone = this.txtPhone.Text.ToString();
        }

        private void txtOrderCode_TextChanged(object sender, EventArgs e)
        {
            String str = this.txtOrderCode.Text.ToString();
            if (!String.IsNullOrEmpty(str))
            {
                var arr = str.Split(Environment.NewLine.ToCharArray());
                var strarr = arr.Where(s => !string.IsNullOrEmpty(s)).ToArray(); //去掉空字符串 得到的结果完美
                List<String> list = new List<string>(strarr);
                this.search.orderNos = list;
            }
            else
            {
                this.search.orderNos = null;
            }
        }

        private void txtDeliveryCode_TextChanged(object sender, EventArgs e)
        {
            String str = this.txtDeliveryCode.Text.ToString();
            if (!String.IsNullOrEmpty(str))
            {
                var arr = str.Split(Environment.NewLine.ToCharArray());
                var strarr = arr.Where(s => !string.IsNullOrEmpty(s)).ToArray(); //去掉空字符串 得到的结果完美
                List<String> list = new List<string>(strarr);
                this.search.expressCodes = list;
            }
            else
            {
                this.search.expressCodes = null;
            }
        }

        private void txtUserName_TextChanged(object sender, EventArgs e)
        {
            this.search.consignee = this.txtUserName.Text.ToString();
        }


        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void txtStartTime_TextChanged(object sender, EventArgs e)
        {
            this.search.startTime = this.txtStartTime.Text;
        }

        private void txtEndTime_TextChanged(object sender, EventArgs e)
        {
            this.search.endTime = this.txtEndTime.Text;
        }


        private void txtBatchCode_TextChanged(object sender, EventArgs e)
        {
            this.search.printBatchNo = this.txtBatchCode.Text.ToString();
        }

        private void txtSortStart_TextChanged(object sender, EventArgs e)
        {
            Int32 i = 0;
            if (Int32.TryParse(this.txtSortStart.Text, out i))
            {
                this.search.printSerialStart = i;
            }
            else
            {
                this.txtSortStart.Text = String.Empty;
                this.search.printSerialStart = 0;
            }
        }

        private void txtSortEnd_TextChanged(object sender, EventArgs e)
        {
            Int32 i = 0;
            if (Int32.TryParse(this.txtSortEnd.Text, out i))
            {
                this.search.printSerialEnd = i;
            }
            else
            {
                this.txtSortEnd.Text = String.Empty;
                this.search.printSerialEnd = 0;
            }
        }

        private void skinComboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.search.printStatus = this.skinComboBox2.SelectedIndex;
        }

        private void comboBoxExProvince_MouseClick(object sender, MouseEventArgs e)
        {
            this.comboBoxExProvince.BringToFront();
        }

        private void comboBoxExProvince_TextChanged(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.comboBoxExProvince.Text))
            {

            }
        }

        private void skinComboBoxType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.skinComboBoxType.SelectedIndex == 0)
            {
                this.search.platformId = 0;
            }
            else if (this.skinComboBoxType.SelectedIndex == 1)
            {
                this.search.platformId = 1;
            }
            else if (this.skinComboBoxType.SelectedIndex == 2)
            {
                this.search.platformId = 4;
            }
        }
        
        // 智能打印
        private void intellBtn_Click(object sender, EventArgs e)
        {
            this.Hide();
            new FrmIntelligence().ShowDialog();
            this.Show();
        }

        private void skinDataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            string columnName = this.skinDataGridView1.Columns[e.ColumnIndex].Name;
            System.Windows.Forms.SortOrder so = this.skinDataGridView1.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection;

            if (so == System.Windows.Forms.SortOrder.Ascending)
            {
                columnName = columnName + " asc";
            }
            if (so == System.Windows.Forms.SortOrder.Descending)
            {
                columnName = columnName + " desc";
            }
            strOrderBy = "" + columnName;
            DataTable dtt = (DataTable)this.skinDataGridView1.DataSource;
            DataTable dtNew = LinqSortDataTable(dtt);
            if (!this.hasBatcode)
            {
                int index = 0;
                String batchCode = DateTime.Now.ToString("yyMMddHHmmss") + "-" + dtNew.Rows.Count.ToString();
                foreach (DataRow dr in dtNew.Rows)
                {
                    index++;
                    dr["序号"] = index.ToString();
                    dr["批次号"] = batchCode;
                }
                this.setData(dtNew);
            }
        }
        public DataTable LinqSortDataTable(DataTable tmpDt, string strOrderBy)
        {
            tmpDt.DefaultView.Sort = strOrderBy;
            return tmpDt.DefaultView.ToTable();
        }

        // 导出功能
        private void exportBtn_Click(object sender, EventArgs e)
        {
            DataTable dtt = (DataTable)this.skinDataGridView1.DataSource;
            if (dtt.Rows.Count > 0)
            {
                saveFileDialog1.Filter = "txt files(*.txt)|*.txt|xls files(*.xls)|*.xls|All files(*.*)|*.*";
                saveFileDialog1.FileName = DateTime.Now.ToString("yyMMddHHmmss") + "-订单.xls";
                saveFileDialog1.DefaultExt = "xml";
                saveFileDialog1.AddExtension = true;
                saveFileDialog1.FilterIndex = 2;
                saveFileDialog1.RestoreDirectory = true;

                DialogResult result = saveFileDialog1.ShowDialog();
                if (result == DialogResult.OK)
                {
                    localFilePath = saveFileDialog1.FileName.ToString();
                    DataTable dtNew = LinqSortDataTable(dtt);
                    DataTable dx = new DataTable();
                    dx.Columns.Add("订单时间", typeof(string));
                    dx.Columns.Add("订单编号", typeof(string));
                    dx.Columns.Add("快递单号", typeof(string));
                    dx.Columns.Add("快递", typeof(string));
                    dx.Columns.Add("收货人姓名", typeof(string));
                    dx.Columns.Add("收货人电话", typeof(string));
                    dx.Columns.Add("省", typeof(string));
                    dx.Columns.Add("市", typeof(string));
                    dx.Columns.Add("区", typeof(string));
                    dx.Columns.Add("详细地址", typeof(string));
                    dx.Columns.Add("商品编码", typeof(string));
                    foreach (DataRow dr in dtNew.Rows)
                    {
                        DataRow dxRow = dx.NewRow();
                        dxRow["订单时间"] = dr["订单时间"];
                        dxRow["订单编号"] = dr["订单编号"];
                        dxRow["快递单号"] = dr["快递单号"];
                        dxRow["快递"] = dr["快递"];
                        dxRow["收货人姓名"] = dr["收货人姓名"];
                        dxRow["收货人电话"] = dr["收货人电话"];
                        dxRow["省"] = dr["省"];
                        dxRow["市"] = dr["市"];
                        dxRow["区"] = dr["区"];
                        dxRow["详细地址"] = dr["详细地址"];
                        dxRow["商品编码"] = dr["商品编码"];
                        dx.Rows.Add(dxRow);
                    }
                    ExportUtils.DataTableToExcel(dx, localFilePath, "@打印数据");
                }
                MessageBox.Show("导出成功","提示");
            }
            else
            {
                MessageBox.Show(@"没有任何数据");
            }
        }

    }
}
